package com.kehutong.wwin.service.service;

import com.kehutong.common.DoveClient;
import com.kehutong.common.enums.CropPattern;
import com.kehutong.common.util.CorpUtils;
import com.kehutong.common.util.Token;
import com.kehutong.wwin.service.entity.Corp;
import com.kehutong.wwin.service.entity.DepartmentMap;
import com.kehutong.wwin.service.util.WwInHttpClient;
import org.coraframework.authz.Subject;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.connection.ThreadLocalCache;
import org.coraframework.util.Objects;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 向客户通发送
 *
 * @author liuzhen(liuxing521a@163.com)
 * @createTime 2020年7月20日下午6:16:25
 */
@WebService("/wwin/event/change_contact")
public class ToKhtDepartmentService {
	
	@Inject
	private JdbcSession jdbcSession;
	@Inject
	private ToWwinDepartmentService wwinDepartmentService;
	@Inject
	private WwInHttpClient httpClient;

	@Inject
	private DoveClient doveClient;
	
	@ReqMapping("/create_party")
	public Object khtCreate(Token token, JSONObject wwJson) throws Exception {
		String cropId=wwJson.getString("ToUserName");
		Corp crop = Pool.get(Corp.class, cropId);
		ThreadLocalCache.current().setCorpId(crop.getKhtid());
		DepartmentMap department = createDepartment(wwJson);

		DepartmentMap map = getDepartmentByWwId(Integer.parseInt(department.getKhtid()));
		if(CorpUtils.getCropPattern(crop.getKhtid())== CropPattern.INNER){
			//部门已经存在
			DepartmentMap dbMap = getDepartmentByWwId(wwJson.getIntValue("Id"));
			if(Objects.nonNull(dbMap)){
				return Result.success();
			}

			JSONObject rs = httpClient.postKht("/basic/department/service/save", cropId, http-> {
				JSONObject toKhtJson = department.toKhtJson();
				toKhtJson.forEach((k, v)->http.addParam(k, v));
			});
			int result = rs.getIntValue("code");
			if (result != 200) {
				return Result.error(result, rs.getString("message"));
			}
		}
		jdbcSession.insert(department);
		
		return Result.success();
	}
	
	@ReqMapping("/update_party")
	public Object khtUpdate(Token token, JSONObject wwJson) throws Exception {
		String cropId=wwJson.getString("ToUserName");
		Corp crop = Pool.get(Corp.class, cropId);
		if(CorpUtils.getCropPattern(crop.getKhtid())== CropPattern.INNER){
			ThreadLocalCache.current().setCorpId(crop.getKhtid());
			DepartmentMap department = getDepartment(wwJson);
			JSONObject rs = httpClient.postKht("/basic/department/service/update", cropId, http-> {
				JSONObject toKhtJson = department.toKhtJson();
				toKhtJson.forEach((k, v)->http.addParam(k, v));
			});

			int result = rs.getIntValue("code");
			if (result != 200) {
				return Result.error(result, rs.getString("message"));
			}
		}
		return Result.success();
	}
	
	@ReqMapping("/delete_party")
	public Object khtDelete(Token token, JSONObject wwJson) throws Exception {
		String cropId=wwJson.getString("ToUserName");
		Corp crop = Pool.get(Corp.class, cropId);
		ThreadLocalCache.current().setCorpId(crop.getKhtid());
		DepartmentMap department = getDepartment(wwJson);
		if(CorpUtils.getCropPattern(crop.getKhtid())== CropPattern.INNER){
			JSONObject rs = httpClient.postKht("/basic/department/service/delete", cropId, http-> {
				http.addParam("id", department.getKhtid());
			});

			int result = rs.getIntValue("code");
			if (result != 200) {
				return Result.error(result, rs.getString("message"));
			}
		}
		jdbcSession.deleteById(department);
		return Result.success();
	}
	
	public DepartmentMap getDepartmentByWwId(int wwid) {
		return Pool.get(DepartmentMap.class, String.valueOf(wwid));
	}


	public List<Integer> getKhtIdByWwinId(JSONArray wwJsonArray) {
		if (Objects.isEmpty(wwJsonArray)) {
			return null;
		}

		List<Integer> departmentList = new ArrayList<>(wwJsonArray.size());
		for (int i  = 0; i < wwJsonArray.size(); i ++) {
			departmentList.add(Integer.parseInt(getKhtIdByWwinId(wwJsonArray.getString(i))));
		}

		return departmentList;
	}

	public String getKhtIdByWwinId(String wwid) {
		if (Objects.isEmpty(wwid)) {
			return null;
		}
		DepartmentMap map = Pool.get(DepartmentMap.class, wwid);
		return map.getKhtid();
	}

	public JSONArray toKhtId(JSONArray wwJsonArray) {
		if (Objects.isEmpty(wwJsonArray)) {
			return null;
		}
		
		JSONArray khtJsonArray = new JSONArray(wwJsonArray.size());
		for (int i  = 0; i < wwJsonArray.size(); i ++) {
			khtJsonArray.add(toKhtId(wwJsonArray.getString(i)));
		}
		
		return khtJsonArray;
	}
	
	public String toKhtId(String wwid) {
		if (Objects.isEmpty(wwid)) {
			return null;
		}
		DepartmentMap map = Pool.get(DepartmentMap.class, wwid);
		return map.getKhtid();
	}
	
	public void save(DepartmentMap map) {
		jdbcSession.insert(map);
	}

	private DepartmentMap createDepartment(JSONObject wwJson) {
		//授权微信企业的CorpID
		String cropId=wwJson.getString("ToUserName");
		Corp crop = Pool.get(Corp.class, cropId);
		DepartmentMap department = Pool.newInstance(DepartmentMap.class, wwJson.getString("Id"));
		department.setName(wwJson.getString("Name"));
		department.setSort(wwJson.getIntValue("Order"));
		department.setKhtid(ToKhtDepartmentService.toKhtId(crop.getKhtid(),wwJson.getString("Id")));
		
		int pid = wwJson.getIntValue("ParentId");
		if (pid != 0) {
			DepartmentMap parent = getDepartmentByWwId(pid);
			department.setPid(String.valueOf(parent.getKhtid()));
		}
		
		return department;
	}

	/**
	 * 获取第三方同步部门映射主键,防止产生重复数据
	 * 首次同步第三方映射数据，保持内建与第三方的数据一致
	 * @return
	 * @throws Exception
	 */
	public Map<String, String> getDepartmentMap() throws Exception{
		JSONObject result = doveClient.post("/kht-bin/wwout/getDepartmentMap",(http)->{
		});

		Map<String,String> employeeMap = new HashMap<>();
		if (result.getIntValue("code") == 200) {
			JSONArray data = result.getJSONArray("data");
			data.forEach(item->{
				JSONObject obj = (JSONObject) item;
				employeeMap.put(obj.getString("id"),obj.getString("khtid"));
			});
		}

		return employeeMap;
	}
	
	private DepartmentMap getDepartment(JSONObject wwJson) {
		DepartmentMap map = getDepartmentByWwId(wwJson.getIntValue("Id"));
		
		map.setName(wwJson.getString("Name"));
		map.setSort(wwJson.getIntValue("Order"));
		int pid = wwJson.getIntValue("ParentId");
		if (pid != 0) {
			DepartmentMap parent = getDepartmentByWwId(pid);
			map.setPid(parent.getKhtid());
		}
		
		return map;
	}

	/**
	 * 根据腾讯部门ID生成部门
	 * @param corpNo
	 * @param id
	 * @return
	 */
	public static String toKhtId(String corpNo, String id) {
		return Subject.encrypt(corpNo + "_" + id.toUpperCase());
	}

	/**
	 * 构建客户通部门标志
	 * 如果第三方没有同步过当前部门，则根据 腾讯给的部门ID+公司编号生成主键
	 * 如果第三方包含当前部门，则获取已有的客户通主键
	 * 其他腾讯给的部门ID+公司编号生成主键
	 * @param thridMap
	 * @param corpNo
	 * @param detpId
	 * @return
	 */
	public static String buildDeptKhtId(Map<String, String> thridMap,String corpNo,String detpId){
		if(Objects.isEmpty(thridMap)){
			return ToKhtDepartmentService.toKhtId(corpNo,detpId);
		}
		if(thridMap.containsKey(detpId)){
			return thridMap.get(detpId);
		}
		return ToKhtDepartmentService.toKhtId(corpNo,detpId);
	}
}
